package com.shanghai.market.plshnaghai.net;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.shanghai.market.plshnaghai.AppApplication;
import com.shanghai.market.plshnaghai.entity.AppData;
import com.shanghai.market.plshnaghai.listeners.OnStringResultListener;
import com.shanghai.market.plshnaghai.publics.LogCat;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * 业务基类,直接返回整个字符串
 * 
 */
public class StringManager {
	private OnStringResultListener onResultListener;
	private static final int VOLLEY_TIMEOUT = 50 * 1000;

	public StringManager() {
		super();
	}

	public void setOnResultListener(OnStringResultListener onResultListener) {
		this.onResultListener = onResultListener;
	}

	public void executeRequest(int method, String url) {
		LogCat.i("url:" + url);
		if (!AppApplication.getInstance().isNetConnected()) {
			handleFailResult("网络未连接!");
			return;
		}

		final StringRequest request = new StringRequest(method, url, responseListener(), errorListener()) {

			@Override
			protected Response<String> parseNetworkResponse(NetworkResponse response) {
				String cookie = response.headers.get("Set-Cookie");
				if (null != cookie) {
					AppData data = AppApplication.getInstance().getAppData();
					data.setCookie(cookie);
					AppApplication.getInstance().saveAppData(data);
					data = null;
				}
				return super.parseNetworkResponse(response);
			}

			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				return AppApplication.getInstance().initHttpHeader();
			}
		};

		request.setRetryPolicy(new DefaultRetryPolicy(VOLLEY_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		RequestManager.addRequest(request, this);
	}

	public void cancelAll() {
		RequestManager.cancelAll(this);
	}

	private void handleSuccessResult(String response) {
		if (this.onResultListener != null) {
			this.onResultListener.onSuccess(response);
		}
	}

	private void handleFailResult(String text) {
		if (this.onResultListener != null) {
			this.onResultListener.onFail(text);
		}
	}

	private ErrorListener errorListener() {
		return new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				final String errorData = error.getMessage();
				LogCat.i("response:" + errorData);
				handleFailResult("连接服务器异常!");
			}
		};
	}

	private Listener<String> responseListener() {
		final Listener<String> listener = new Listener<String>() {

			@Override
			public void onResponse(String result) {
				LogCat.i("response:" + result);
				try {
					JSONObject jsonResult = new JSONObject(result);
					final int status = jsonResult.getInt("status");
					if (status == 0) {
						JSONObject bodyObject = jsonResult.getJSONObject("body");
						handleSuccessResult(bodyObject.toString());
					} else {
						handleFailResult(jsonResult.getString("message"));
					}
				} catch (JSONException ex) {
					ex.printStackTrace();
				}
			}

		};
		return listener;
	}

}
